package de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.nodeImpl;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.espertech.esper.client.EPServiceProvider;

import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.MMOperatorNode;
import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.NodeFactory;

public class CorrelationNodeFactory implements NodeFactory {

	public MMOperatorNode createNode(Element DOMElement,
			Element attachmentsElement, MMOperatorNode parent,
			EPServiceProvider EPService) {

		MMOperatorNode toReturn = new MMOperatorNode();

		// Attributes independent of the children
		toReturn.setOutputStreamName("correlation"
				+ (++MMOperatorNode.nodeLatestDistributedID));
		toReturn.setOutputMetric("correlation");

		toReturn.setParent(parent);

		/*
		 * Parameters to get : correlationKey1, correlationKey2
		 */
		NodeList attachments = null;
		NodeList correlations = attachmentsElement
				.getElementsByTagName("correlation");
		for (int i = 0; i < correlations.getLength(); i++) {
			Element correlation = (Element) correlations.item(i);
			if (((Element) correlations.item(i)).getAttributeNode(
					"correlationID").getNodeValue()
					.equals(
							DOMElement.getAttributeNode("correlationID")
									.getNodeValue())) {
				attachments = correlation.getElementsByTagName("attachment");
			}
		}
		// toReturn.setParameters();

		// Children nodes not for atomic operator like state, duration, count
		// etc.
		/*
		 * NodeList childrenElements = DOMElement.getChildNodes(); if
		 * (childrenElements.getLength() > 0) { List<MMOperatorNode> children =
		 * new ArrayList<MMOperatorNode>(4); for (int i = 0; i <
		 * childrenElements.getLength(); i++) { Element currentChildRoot =
		 * (Element) childrenElements.item(i);
		 * children.add(NodeFactoryManager.getInstance(
		 * currentChildRoot.getLocalName()).createNode( currentChildRoot,
		 * attachmentsElement, toReturn, EPService)); }
		 * 
		 * toReturn.getChildren(); toReturn.setChildren(children); }
		 */

		String statementString = null;

		statementString
				.concat("INSERT INTO "
						+ toReturn.getOutputStreamName()
						+ " SELECT "
						+ " de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.EventUtils.addInCorrelationSet(a.processInstanceID, b.processInstanceID) AS correlationSet "
						+ " FROM PATTERN [(every a = de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.ProcessVariableEvent -> b = de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.ProcessVariableEvent("
						+ toReturn.getParameters().get("correlationKey1")
						+ " = "
						+ toReturn.getParameters().get("correlationKey2")
						+ ")]");

		// Creation of the statement that is directly registered in the engine !
		toReturn.setStatement(EPService.getEPAdministrator().createEPL(
				statementString));

		return toReturn;
	}

}
